using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Data;

namespace ArchSoft
{
    public class SynchronizeDrawingLayout
    {
        string _sourcePath;       
       
        List<string> EditedFiles_;

        public SynchronizeDrawingLayout(string source, List<string> EditedFiles)
        {
            _sourcePath = source;
            EditedFiles_ = EditedFiles;
        }

        public bool DeleteTarget()
        {
            // Delete .bak file
            try
            {
                DirectoryInfo source = new DirectoryInfo(_sourcePath);
                foreach (DirectoryInfo subDir in source.GetDirectories())
                {
                    foreach (FileInfo file in subDir.GetFiles())
                    {
                        if (!file.Extension.Equals(".dwg") && !file.Extension.Equals(".dwt"))
                        {
                            file.Delete();
                        }
                    }
                }
                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
        }

        private void DeleteTempFile()
        {
            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (FileInfo adrawing in issueWindow.GetFiles())
                adrawing.Delete();

            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
                if (dir.Name.ToLower().Contains("reference"))
                    dir.Delete(true);
                else
                {
                    foreach (FileInfo adrawing in dir.GetFiles())
                        if (!adrawing.Extension.Contains("dwg") && !adrawing.Extension.Contains("dwt"))
                            adrawing.Delete();
                }
        }

        public string GenerateScriptFile()
        {
            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");


            for (int i = 0; i < EditedFiles_.Count - 1; i++)
            {
                ScriptForDetachTitle(wr, false, EditedFiles_[i].Split('*')[0], EditedFiles_[i].Split('*')[2], EditedFiles_[i].Split('*')[1]);
            }

            ScriptForDetachTitle(wr, true, EditedFiles_[EditedFiles_.Count - 1].Split('*')[0], EditedFiles_[EditedFiles_.Count - 1].Split('*')[2], EditedFiles_[EditedFiles_.Count - 1].Split('*')[1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;
        }

        public string RunSciptFile(string filePath)
        {
            AutocadHelper helper = AutocadHelper.Instance;
            return helper.RunAutoCadScript(filePath, true);
        }

        public string Process()
        {
            string str = "";

           bool tpd = DeleteTarget(); if (!tpd) { return ""; }
            string scriptFile = GenerateScriptFile();
            if (scriptFile == "")
                return "";
            str = RunSciptFile(scriptFile);
            DeleteTempFile();
            return str;
        }

        public void ScriptForDetachTitle(StreamWriter wr, bool lastDrawing, string fileName, string ScaleI,string SizeI)
        {
            string Tempfile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Trang\\Architecture\\Layout";
            bool Found = false;
            foreach (string file in Directory.GetFiles(Tempfile))
            {
                if (Path.GetExtension(file).ToLower() != ".dwt")
                    continue;
                if (Path.GetFileNameWithoutExtension(file).Split('_').Length < 2)
                    continue;
                if (Path.GetFileNameWithoutExtension(file).Split('_')[2] == ScaleI && Path.GetFileNameWithoutExtension(file).Split('_')[1] == SizeI)
                {
                    Tempfile = file;
                    Found = true;
                    break;
                }
            }

            wr.WriteLine("open \"" + fileName + "\"");

            if (!Found)
                goto pug;

            //Go to Layout Space
            wr.WriteLine("TILEMODE");
            wr.WriteLine("0");

            for (int i = 0; i < 10; i++)
            {
                //Delete Old Layout
                wr.WriteLine("-LAYOUT");
                wr.WriteLine("D");
                wr.WriteLine("");//10 times
            }

            //Rename Old Layout
            wr.WriteLine("-LAYOUT");
            wr.WriteLine("R");
            wr.WriteLine("");
            wr.WriteLine("Trang");

            //Insert Template Layout
            wr.WriteLine("-LAYOUT");
            wr.WriteLine("T");
            wr.WriteLine("\"" + Tempfile + "\"");//Select Template File
            wr.WriteLine(ScaleI);//Select Drawing Scale

            //Delete Old Layout
            wr.WriteLine("");
            wr.WriteLine("D");
            wr.WriteLine("Trang");

        pug:
            //Rename Layout
            //wr.WriteLine("");
            //wr.WriteLine("R");
            //wr.WriteLine("");
            //wr.WriteLine(Path.GetFileNameWithoutExtension(fileName).Split('_')[0]);//Drawing Code
          
            wr.WriteLine("QSAVE");

            if (!lastDrawing)
            {
                wr.WriteLine("Close");
            }
        }      
    }
}
